<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>编辑 - MdbSystem</title>
  <link rel="stylesheet" href="https://unpkg.com/mdui@1.0.1/dist/css/mdui.min.css">
  <style>
    .top-alert {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      background-color: #F9C207;
      color: white;
      font-weight: bold;
      text-align: center;
      padding: 4px 0;
      box-sizing: border-box;
      z-index: 1000;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      font-family: Arial, sans-serif;
      font-size: 16px;
    }
    .file-upload {
      margin-top: 1%;
      border: 2px dashed #ccc;
      padding: 20px;
      text-align: center;
      margin-bottom: 20px;
    }
    .file-upload:hover {
      border-color: #2196F3; /* 蓝色 */
    }
    #fileResult {
      margin-top: 10px;
      color: green;
    }
    #formContainer {
      width: 600px;
      margin: 0 auto;
    }
  </style>
</head>
<body class="mdui-theme-primary-blue mdui-theme-accent-blue">
  <div id="app">
    <div class="top-alert">⚠ 您正在进行编辑操作 ⚠</div>

    <!-- 上传 -->
    <div class="file-upload mdui-shadow-2" id="uploadArea">
      <input type="file" id="fileInput" style="display: none;" accept="image/*" />
      <label for="fileInput" id="uploadLabel" class="mdui-ripple">直接上传以把文件丢到服务器上托管</label>
      <div id="fileResult" style="display: none;">
        文件上传成功！地址：<span id="fileUrl"></span>
        <button class="mdui-btn mdui-btn-raised mdui-ripple" onclick="copyToClipboard()">复制地址</button>
      </div>
    </div>

    <!-- 表单 -->
    <div id="formContainer" class="mdui-shadow-2 mdui-p-a-4">
      <input type="hidden" id="articleId">
      <div class="mdui-textfield">
        <label class="mdui-textfield-label">标题内容</label>
        <input class="mdui-textfield-input" type="text" id="title" placeholder="请输入标题">
      </div>
      <div class="mdui-textfield">
        <label class="mdui-textfield-label">Markdown正文内容</label>
        <textarea class="mdui-textfield-input" id="content" placeholder="请输入Markdown内容" rows="5"></textarea>
      </div>
      <div class="mdui-textfield">
        <label class="mdui-textfield-label">标签内容</label>
        <input class="mdui-textfield-input" type="text" id="tags" placeholder="请输入标签，用空格分隔">
      </div>
      <div class="mdui-textfield">
        <label class="mdui-textfield-label">类别选择</label>
        <select class="mdui-select" id="category">
          <option value="category1">数学题目</option>
          <option value="category2">物理题目</option>
          <option value="category3">生物知识点</option>
        </select>
      </div>
      <div style="text-align: center;">
        <button class="mdui-btn mdui-btn-raised mdui-ripple mdui-color-theme-accent" onclick="submitForm()">提交表单</button>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/mdui@2.1.3/mdui.global.min.js"></script>
  <script>
    // URL
    function getQueryParam(name) {
      const params = new URLSearchParams(window.location.search);
      return params.get(name);
    }

    async function loadArticleData() {
      const articleId = getQueryParam('id');
      if (!articleId) {
        alert('缺少文章ID参数');
        // window.location.href = '/';
        return;
      }

      try {
        const response = await fetch(`/detailData?id=${articleId}`);
        const data = await response.json();

        if (data.error_code === 0) {
          document.getElementById('articleId').value = data.id;
          document.getElementById('title').value = data.title;
          document.getElementById('content').value = data.content;
          document.getElementById('tags').value = data.tags;
          document.getElementById('category').value = data.category;
        } else {
          alert('加载数据失败: ' + data.message);
          window.location.href = '/';
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        alert('加载数据失败，请检查网络连接');
        window.location.href = '/';
      }
    }
    document.addEventListener('DOMContentLoaded', loadArticleData);
    const fileInput = document.getElementById('fileInput');
    const uploadArea = document.getElementById('uploadArea');
    const uploadLabel = document.getElementById('uploadLabel');
    const fileResult = document.getElementById('fileResult');
    const fileUrl = document.getElementById('fileUrl');

    uploadArea.addEventListener('dragover', (e) => {
      e.preventDefault();
      uploadArea.style.borderColor = '#2196F3';
    });

    uploadArea.addEventListener('dragleave', () => {
      uploadArea.style.borderColor = '#ccc';
    });

    uploadArea.addEventListener('drop', (e) => {
      e.preventDefault();
      uploadArea.style.borderColor = '#ccc';
      const file = e.dataTransfer.files[0];
      if (file) {
        fileInput.files = e.dataTransfer.files;
        uploadFile(file);
      }
    });

    uploadLabel.addEventListener('click', () => {
      fileInput.click();
    });

    fileInput.addEventListener('change', (e) => {
      const file = e.target.files[0];
      if (file) {
        uploadFile(file);
      }
    });

    function uploadFile(file) {
      const formData = new FormData();
      formData.append('file', file);

      fetch('/api/upload', {
        method: 'POST',
        body: formData
      })
      .then(response => response.json())
      .then(data => {
        fileResult.style.display = 'block';
        fileUrl.textContent = data.FullPath;
      })
      .catch(error => {
        console.error('Error:', error);
      });
    }

    function copyToClipboard() {
      const range = document.createRange();
      range.selectNode(fileUrl);
      window.getSelection().addRange(range);
      try {
        document.execCommand('copy');
      } catch (err) {
        console.error('复制失败', err);
      }
      window.getSelection().removeAllRanges();
    }

    function submitForm() {
      const formData = {
        id: document.getElementById('articleId').value,
        title: document.getElementById('title').value,
        content: document.getElementById('content').value,
        tags: document.getElementById('tags').value,
        category: document.getElementById('category').value
      };

      fetch('/update', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(formData)
      })
      .then(response => response.json())
      .then(data => {
        if (data.error_code == 1){
          alert("错误：" + data.message)
        }
        else{
          alert('表单提交成功！');
          window.location.href = "/"
        }
      })
      .catch(error => {
        console.error('Error:', error);
      });
    }
  </script>
</body>
</html>